package ru.sanluck.books;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class DefaultBookCrudService implements BookCrudService {

    private final BookRepository bookRepository;
    private final BookMapper bookMapper;

    @Transactional
    @Override
    public void createBook(String name, String author, String barcode) {
        BookEntity book = new BookEntity();
        book.setName(name);
        book.setAuthor(author);
        book.setBarcode(barcode);
        bookRepository.save(book);
    }

    @Override
    public Book getBook(Integer id) {
        return bookRepository.findById(id)
                .map(bookMapper::toDomain)
                .orElse(null);
    }

    @Override
    public List<Book> getBooks(String name) {
        List<Book> books = new ArrayList<>();

        books.addAll(bookRepository.findAllByNameContainsIgnoreCase(name)
                .stream()
                .map(bookMapper::toDomain)
                .toList());

        return books;
    }

    @Override
    public void deleteBook(Integer id) {
        //not implemented yet
    }
}
